package com.yang.designmode.Authentication;

public class DefaultApiAuthenticatorImpl implements ApiAuthenticator{

    private CredentialStorage credentialStorage;

    public DefaultApiAuthenticatorImpl(CredentialStorage credentialStorage) {
        this.credentialStorage = credentialStorage;
    }

    /**
     * 权限校验
     * @param url
     */
    @Override
    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.createFromFullUrl(url);
        this.auth(apiRequest);
    }

    /**
     * 做认证的校验
     * @param request
     */
    @Override
    public void auth(ApiRequest request) {
        //获取到AppID token和时间戳
        String appId = request.getAppId();
        String token = request.getToken();
        long timestamp = request.getTimestamp();
        // 获取token
        AuthToken authToken = new AuthToken(token, timestamp);
        // 判断是否过期
        if(authToken.isExpired()){
            throw new RuntimeException("token expired");
        }
        // 获取密码
        String password = credentialStorage.getPasswordByAppId(appId);
        String baseUrl = request.getBaseUrl();
        AuthToken newToken = AuthToken.generateToken(baseUrl, timestamp, request);
        if(!authToken.match(newToken)){
            throw new RuntimeException("token not match");
        }
    }
}
